#include "string.h"
#include "stdio.h"
#include "config.h"

#include "subcribe.h"

static short FrameSubId = 1;//报文标识符

int sucribe_subcribe_topic(int maxQos,int sockfd)
{
	unsigned char frame[MAX_SEND_BUFF_SIZE];
	int frameLen = 0;
	int remainLen = 0;
	unsigned char offset=0;

	if(sockfd == -1)
	{
		printf("%s():invalid socket\n",__func__);
		return -1;
	}

	//printf("%s():start\n",__func__);

	memset(frame,0,sizeof(frame));    

	//bit[4-7]:消息类型
    frame[0] = MQTT_MSG_SUBCIRBE;
    frame[0] |= 0X02;//SUBSCRIBE 控制报固定报头的第 3,2,1,0 位是保留位， 必须分别设置为 0,0,1,0,

	remainLen = strlen(TOPIC_SUBCIRBE)+2+1+2;//主题长度+主题+qos等级+报文标识符

	// Remaining Length，剩余长度
	if (remainLen <= 127) 
	{
	   frame[1] = remainLen;
	   offset=2;
	} 
	else 
	{
	   // first byte is remainder (mod) of 128, then set the MSB to indicate more bytes
	   frame[1] = remainLen % 128;
	   frame[1] = frame[1] | 0x80;
	   // second byte is number of 128s
	   frame[2] = remainLen / 128;
		offset=3;
	}

    frame[offset++] = ((FrameSubId&0XFF00)>>8);
    frame[offset++] = ((FrameSubId&0x00FF));

	FrameSubId++;
    
	frame[offset++] = (strlen(TOPIC_SUBCIRBE)>>8);
	frame[offset++] = (strlen(TOPIC_SUBCIRBE)&0XFF);

	memcpy(&frame[offset],TOPIC_SUBCIRBE,strlen(TOPIC_SUBCIRBE));
	offset+=strlen(TOPIC_SUBCIRBE);

    frame[offset++] = maxQos;//最大报文安全等级

	//config_printf_hex(frame,offset);

	printf("sucribe_subcribe_topic():subcribe topic:%s\n",TOPIC_SUBCIRBE);

    return (config_mqtt_write(sockfd,frame,offset));
}

//获得报文标识符
int subcribe_get_frame_id()
{
    return FrameSubId;
}